<template>
  <el-card class="box-card">
    <el-page-header @back="$router.go(-1)">
      <template #content>
        <div class="flex items-center">
          <span class="text-large font-600 mr-3"> {{ pageTitle }}</span>
        </div>
      </template>
      <template #extra>
        <div class="flex items-center">
          <el-button
            type="primary"
            class="ml-2"
            @click="onSubmit(courseInfoFormRef)"
            :disabled="saveBtnDisabled"
            >提交</el-button
          >
        </div>
      </template>
    </el-page-header>

    <el-steps
      style="margin-top: 18px; caret-color: transparent"
      :space="200"
      :active="currentStep"
      finish-status="success"
      simple
    >
      <el-step title="基本信息" :icon="Edit" @click="currentStep = 0" />
      <el-step title="课程图片" :icon="Picture" @click="currentStep = 1" />
      <el-step
        title="销售及活动信息"
        :icon="ShoppingCart"
        @click="currentStep = 2"
      />
      <el-step title="课程详情" :icon="Document" @click="currentStep = 3" />
    </el-steps>
    <el-form
      :model="courseInfo"
      :rules="courseInfoRules"
      ref="courseInfoFormRef"
      label-width="120"
    >
      <div v-show="currentStep === 0" style="margin-top: 26px">
        <el-form-item prop="title" label="课程标题">
          <el-input
            v-model="courseInfo.title"
            placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>

        <!-- 所属分类 TODO -->
        <el-form-item label="课程分类" prop="cat_id">
          <!-- options用来指定数据源 -->
          <!-- props用来指定数据对象 -->
          <el-cascader
            placeholder="请下拉选择分类，如无此分类，请至课程分类新增分类信息"
            style="width: 50%; caret-color: transparent"
            :append-to-body="false"
            v-model="selectedKeys"
            :options="parentCateList"
            :props="props"
            @change="handleChange"
            @focus="getParentCateList"
            clearable
        /></el-form-item>

        <!-- 课程讲师 TODO -->
        <el-form-item label="课程讲师" prop="teacher">
          <el-input
            style="width: 50%"
            v-model="courseInfo.teacher"
            placeholder="林间有风"
          />
        </el-form-item>

        <!-- 总课时 -->
        <el-form-item label="总课时" prop="lesson_num">
          <el-input-number
            :min="0"
            :max="9999"
            v-model="courseInfo.lesson_num"
          />
        </el-form-item>

        <!-- 课程简介 TODO -->
        <!-- 课程简介-->
        <el-form-item label="课程简介" prop="brief">
          <el-input
            v-model="courseInfo.brief"
            placeholder="课程简介，不超过100个字"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </div>
      <div v-show="currentStep === 1">
        <el-form-item
          label="课程封面："
          style="margin-top: 30px"
          prop="cover_url"
        >
          <ImageUpload v-model="courseInfo.cover_url"></ImageUpload>
          <!-- <span>{{ courseInfo.cover_url }}</span> -->
        </el-form-item>
      </div>
      <div style="margin-top: 26px" v-show="currentStep === 2">
        <el-form-item label="售卖价格" prop="discounts">
          <el-input-number
            v-model="courseInfo.discounts"
            :min="0"
            :precision="2"
            :step="0.1"
            :max="99999"
          />
        </el-form-item>
        <el-form-item label="课程原价" prop="price">
          <el-input-number
            v-model="courseInfo.price"
            :min="0"
            :precision="2"
            :step="0.1"
            :max="99999"
          />
        </el-form-item>
        <el-form-item label="课程销量">
          <el-input-number v-model="courseInfo.sales" />
        </el-form-item>
        <el-form-item label="活动标签" prop="discountsTag">
          <el-input v-model="courseInfo.discountsTag" />
        </el-form-item>
      </div>
      <div v-show="currentStep === 3" style="margin-top: 26px">
        <el-form-item label="课程详情:">
          <TextEditor v-model="courseInfo.details"></TextEditor>
        </el-form-item>
      </div>
      <div class="form-bottom-btn" style="margin-top: 26px">
        <el-button v-show="currentStep !== 0" @click="currentStep--"
          >上一步</el-button
        >
        <el-button v-show="currentStep !== 3" @click="currentStep++"
          >下一步</el-button
        >
        <el-button
          v-show="currentStep == 3"
          type="primary"
          @click="onSubmit(courseInfoFormRef)"
          :disabled="saveBtnDisabled"
          >提交</el-button
        >
      </div>
    </el-form>

    <!-- <el-button style="margin-top: 20px" @click="next">Next step</el-button> -->
  </el-card>
</template>

<script setup lang="ts">
import { Edit, ShoppingCart, Picture, Document } from '@element-plus/icons-vue'
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { layer } from '@layui/layer-vue'
import { getCategory } from '@/api/category/index'
import { courseInfoData } from '@/api/course/type'
//引入图片上传组件
import ImageUpload from '@/views/courses/components/ImageUpload.vue'
//引入富文本编辑器
import TextEditor from './components/TextEditor.vue'
//导入保存课程信息接口
import { getCourseInfoById, saveCourseInfo } from '@/api/course/index'
import type { FormInstance, FormRules } from 'element-plus'
//导入路由
import { useRouter, useRoute } from 'vue-router'

//获取路由器对象
let $router = useRouter()
let route = useRoute()

// let courseId = ref<number>(1)
// //通过路由参数获取课程ID

let pageTitle = ref('')

//按钮是否禁用，默认不禁用
let saveBtnDisabled = ref(false)

let currentStep = ref(0)

let initData = () => ({
  //课程标题
  title: '',
  //总课时
  lesson_num: 0,
  //分类的id
  cat_id: 0,
  //课程讲师
  teacher: '',
  //课程简介
  brief: '',
  //课程封面地址
  cover_url: '',
  //销售价格
  discounts: 0,
  //课程原价
  price: 0,
  //销量
  sales: 0,
  //活动标签
  discountsTag: '',
  //课程详情
  details: ''
})

//课程基本信息
let courseInfo = <courseInfoData>reactive(initData())

// 通过路由参数获取课程ID
let courseId = route.query.courseId
//console.log(courseId)

const getCourInfo = async () => {
  try {
    let _courseId = Number(courseId)
    const res = await getCourseInfoById(_courseId)
    return res.data
  } catch (err) {
    ElMessage({
      type: 'error',
      message: '获取课程信息失败！'
    })
    throw new Error('获取课程信息失败！')
  }
}

if (courseId) {
  let res = getCourInfo()
  res.then((data) => {
    console.log(data)
    courseInfo.title = data.title
    courseInfo.teacher = data.teacher
    courseInfo.brief = data.brief
    courseInfo.cover_url = data.cover_url
    courseInfo.discounts = data.discounts

    console.log(typeof courseInfo.discounts)
    courseInfo.price = data.price
    courseInfo.sales = data.sales
    courseInfo.discountsTag = data.discountsTag
    courseInfo.details = data.details
    courseInfo.cat_id = data.cat_id
    console.log(data, '....')
  })

  pageTitle.value = '编辑课程'
} else {
  pageTitle.value = '新建课程'
}

//获取表单元素
const courseInfoFormRef = ref<FormInstance>()

const checkCat = (rule: any, value: any, callback: any) => {
  console.log(rule, '11')
  if (!value) {
    return callback(new Error('请选择分类'))
  } else {
    callback()
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('Please input digits'))
    } else {
      callback()
    }
  }, 1000)
}

//课程基本信息表单的验证规则对象
const courseInfoRules = <FormRules>reactive({
  title: [
    { required: true, message: '请输入课程标题', trigger: 'blur' },
    {
      min: 3,
      max: 30,
      message: '课程标题最少2位，最多不超过30位！',
      trigger: 'blur'
    }
  ],
  cat_id: [{ required: true, validator: checkCat, trigger: 'change' }],
  teacher: [
    {
      required: true,
      message: '请输入讲师姓名',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 30,
      message: '讲师姓名最少2位，最多不超过20位！',
      trigger: 'blur'
    }
  ],
  lesson_num: [
    {
      required: true,
      message: '请输入课程总课时，如不确定可输入0,最大为9999',
      trigger: 'blur'
    }
  ],
  brief: [
    {
      required: true,
      message: '请输入课程简介',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 100,
      message: '课程简介最少2位，最多不超过100位！',
      trigger: 'blur'
    }
  ],
  cover_url: [
    {
      required: true,
      message: '请上传课程封面',
      trigger: 'change'
    }
  ],
  discounts: [
    {
      required: true,
      message: '请输入课程销售价格，如免费默认为0',
      trigger: 'blur'
    }
  ],
  price: [
    {
      required: true,
      message: '请输入课程销售原价，如免费默认为0',
      trigger: 'blur'
    }
  ],
  discountsTag: [
    {
      required: false,
      message: '请输入活动标签',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 30,
      message: '活动标签最少2位，最多不超过20位！',
      trigger: 'blur'
    }
  ]
})

let data = ref([])

//======以下为课程分类相关代码=====
//级联选择器配置对象
const props = {
  //指定选定的值
  value: 'id',
  //指定看到的属性
  label: 'title',
  //指定嵌套的属性
  children: 'children',
  //次级菜单的展开方式,hover或者click
  expandTrigger: 'hover',
  // 是否严格的遵守父子节点不互相关联,每一级都可以选择
  checkStrictly: true
}

//选中的父级分类的Id数组，必须是数组
let selectedKeys = reactive([])

// Object.assign(selectedKeys, [2, 5])
// console.log(selectedKeys)

//级联选择器，父级分类列表
let parentCateList = <[]>reactive([])

//获取父级分类的数据列表
const getParentCateList = async () => {
  // 在组件挂载后执行的代码
  const res = await getCategory()

  //合并，不破坏响应式
  Object.assign(parentCateList, res.data)
  //这中写法不可以，会破坏响应式
  //parentCateList = res.data

  // console.log(parentCateList, 'pp')

  return parentCateList
}

//通过最终分类的ID查询父类的id，组成数组
const getParentArray = (data: any, val: any): any => {
  for (var i = 0; i < data.length; i++) {
    //console.log(data[i], 'i1')
    if (data[i] && data[i].id == val) {
      //  console.log(data[i], 'i')
      return []
    }
    if (data[i] && data[i].children) {
      var d = getParentArray(data[i].children, val)
      if (d) return d.concat(data[i].id)
    }
  }
}

//级联选择器的选中项发生变化就会触发
const handleChange = () => {
  console.log(selectedKeys)

  // 如果selectedKeys数组总的length大于0，证明选中父级分裂、
  // 反之，就说明没有选中任何父级分类
  if (Array.isArray(selectedKeys) && selectedKeys.length > 0) {
    //父级分类的Id
    courseInfo.cat_id = selectedKeys[selectedKeys.length - 1]
    return
  } else {
    courseInfo.cat_id = NaN
  }

  console.log(courseInfo.cat_id)
}

//课程表单提交事件
const onSubmit = async (courseInfoFormRef: FormInstance | undefined) => {
  if (!courseInfoFormRef) return
  await courseInfoFormRef.validate(async (valid, fields) => {
    //验证通过执行保存课程发放
    if (valid) {
      console.log(courseInfo)
      try {
        const res = await saveCourseInfo(courseInfo)
        console.log(res)
        layer.msg(`${res.msg}，跳转课程列表页面...`, {
          icon: 6,
          time: 2000
        })
        saveBtnDisabled = ref(true)
        //提示成功信息
        // ElMessage({
        //   type: 'success',
        //   message: '新增课程成功，跳转课程列表页面！'
        // })

        $router.push('/courses/CoursesIndex')
      } catch (err) {
        //提示错误信息
        console.log(err)
        ElMessage({
          type: 'error',
          message: '新增课程失败'
        })
      }
    } else {
      layer.msg('添加课程失败，请检查表单！', { icon: 5, time: 2000 })
      console.log('error submit!', fields)
    }
  })
}

onMounted(async () => {
  // 在组件挂载后执行的代码
  const res = await getCategory()
  //  console.log(res.data)
  data.value = res.data

  //如果是编辑，则获得之前的分类
  if (courseId) {
    getParentCateList().then(async (data) => {
      //   console.log(courseInfo.cat_id)
      const selectsArr = await getParentArray(data, courseInfo.cat_id)
      console.log(selectsArr, 'sel')
      selectsArr.reverse()
      selectsArr.push(courseInfo.cat_id)
      Object.assign(selectedKeys, selectsArr)
    })
  }
})
</script>

<style scoped>
.el-step {
  cursor: pointer;
}
/* .el-form{
  padding:0px 180px 0px 0px;
} */
.form-bottom-btn {
  display: flex;
  justify-content: center;
}
</style>
